﻿package com.projects.xenia;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.projects.xenia.global_modules.MainGlobalModule;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainReturnActivity  extends Activity {

	private final Context Ctx = this;
	
	private Documents_Return DocumentClass;
	
	private final int IDD_ReturnDateDialog = 0;
	private final int IDD_ReturnExecuteDateDialog = 1;	
	private final int IDD_ReturnAccTypeDialog = 2;
	private final int IDD_ReturnFirmDialog = 3;
	private final int IDD_ReturnDepartmentDialog = 4;	
	
	private final int IDR_CustomerSelect = 0;
	private final int IDR_GoodsSelect = 1;
	private final int IDR_CommentsSelect = 2;
	
	private ImageView ReturnGpsState;
	private ImageView ret_goodsopen;
	private ImageView ret_docgoodsopen;
	private ImageView return_backward;
	
	private Button ReturnDate;
	private Button ReturnExecuteDate;
	
	private Button ReturnCustomer;	
	
	private Button ReturnAccType;
	private Button ReturnFirm;
	private Button ReturnDepartment;	
	private Button ReturnComments;
	
	private CheckBox ReturnType;
	
	private Cursor ReturnAccTypeCursor; 
	private Cursor ReturnFirmCursor; 
	private Cursor ReturnDepartmentCursor;
	
	private static TextView ReturnTotalReturnSum;

    public void FinishActivity () { 
    	
    	DocumentClass.Head.state = 1;
    	DocumentClass.Head.verstamp++;
    	DocumentClass.UpdateDoc();
    	DocumentClass.FinishDoc ();
    	finish();
    	
    }
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		MainGlobalModule.Documents_Location.StopLocation();
		MainGlobalModule.Documents_Location = null;
	}
	
	protected Cursor GetCursorByTable (String DB_TABLE) {
		return (MainGlobalModule.DBE.rawQuery("select id as _id, descr as descr from "+DB_TABLE+" order by descr", null));		
	}		

	@Override
	public Object onRetainNonConfigurationInstance() {
		return (DocumentClass);	
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {		
		super.onCreate(savedInstanceState);
	

		if (MainGlobalModule.SettingsCollection.get("ManagerId").equals("")) {
			Toast xtoast = Toast.makeText(this, "Устройство не авторизовано !!!", 10);
			xtoast.show();
			finish();
		}
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);            
	    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
		
		setContentView(R.layout.return_main_form);		
			
		Bundle DocExtras;
		DocExtras = getIntent().getExtras();
		
		DocumentClass = (Documents_Return) getLastNonConfigurationInstance();
		
		if (DocumentClass== null) {			
			DocumentClass = new Documents_Return ();
			
			if (DocExtras!=null) {
				if (DocExtras.getString("DocId")!=null) {
					DocumentClass.OpenDoc(DocExtras.getString("DocId"));
					}
				else {
					DocumentClass.NewDoc();
					DocumentClass.Head.customers_id = DocExtras.getString("CustomerId");
					}
			}	
			else {
				DocumentClass.NewDoc();
			}			
		}		
		
		
		MainGlobalModule.DocumentClass = DocumentClass; 
		
		ReturnGpsState = (ImageView) findViewById(R.id.ReturnGpsState);
		ReturnGpsState.setVisibility(View.INVISIBLE);
		
		if (MainGlobalModule.Documents_Location==null) {
			MainGlobalModule.Documents_Location = new Documents_Location();
			MainGlobalModule.Documents_Location.StartLocation(this, MainGlobalModule.DocumentsType.Return, DocumentClass.Head.id,ReturnGpsState);
		}
		
		ReturnDate = (Button) findViewById(R.id.ReturnDate);
		//ReturnDate.setOnClickListener(ReturnDateDialog);
		RefreshDate (ReturnDate,DocumentClass.Head.date_create);		
		
		ReturnExecuteDate = (Button) findViewById(R.id.ReturnExecuteDate);
		//ReturnExecuteDate.setOnClickListener(ReturnExecuteDateDialog);
		RefreshDate (ReturnExecuteDate,DocumentClass.Head.date_execute);
		
		ReturnCustomer = (Button) findViewById(R.id.ReturnCustomer);
		ReturnCustomer.setOnClickListener(ReturnCustomerSelect);
		ReturnCustomer.setOnLongClickListener(CustomerLongSelect);		
		RefreshByCursor (ReturnCustomer , "xref_customers", DocumentClass.Head.customers_id);	
		
		ReturnAccTypeCursor = GetCursorByTable ("xenum_AccType");
		ReturnAccType = (Button) findViewById(R.id.ReturnAccType);
		ReturnAccType.setOnClickListener(ReturnAccTypeDialog);
		RefreshByCursor (ReturnAccType , "xenum_acctype", DocumentClass.Head.acctype);
		
		ReturnFirmCursor = GetCursorByTable ("xref_firms");
		ReturnFirm = (Button) findViewById(R.id.ReturnFirm);
		ReturnFirm.setOnClickListener(ReturnFirmDialog);
		RefreshByCursor (ReturnFirm , "xref_firms", DocumentClass.Head.firms_id);
		
		ReturnDepartmentCursor = GetCursorByTable ("xref_departments");
		ReturnDepartment = (Button) findViewById(R.id.ReturnDepartment);
		ReturnDepartment.setOnClickListener(ReturnDepartmentDialog);
		RefreshByCursor (ReturnDepartment , "xref_departments", DocumentClass.Head.departments_id);
		
		ReturnTotalReturnSum = (TextView) findViewById(R.id.ReturnTotalReturnSum);		
		RefreshByDecimalValue (ReturnTotalReturnSum,DocumentClass.Head.total_returnsum);
		
		ReturnComments = (Button) findViewById(R.id.ReturnCommentsButton);
		ReturnComments.setOnClickListener(ReturnCommentsButton_Click);		
		
		RefreshMultipleByCursor (ReturnComments,"xdoc_Returns_D");
	
		ReturnType = (CheckBox)findViewById(R.id.ReturnType);
		ReturnType.setChecked(!(DocumentClass.Head.return_type==0));
		ReturnType.setOnCheckedChangeListener(new OnCheckedChangeListener() {			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				DocumentClass.Head.return_type = ReturnType.isChecked()?1:0; 
			}
		});
		
		ret_goodsopen = (ImageView)findViewById(R.id.ret_goodsopen);
		ret_goodsopen.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				OpenGoodsSelect();	
			}
		});
		
		ret_docgoodsopen = (ImageView)findViewById(R.id.ret_docgoodsopen);
		ret_docgoodsopen.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				OpenDocContents();
			}
		});		
		
		return_backward = (ImageView)findViewById(R.id._backward);
		return_backward.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				FinishActivity ();				
			}
		});
		
		
	}
	
	private OnLongClickListener CustomerLongSelect = new OnLongClickListener() {		
		@Override
		public boolean onLongClick(View v) {
			
			if (DocumentClass.Head.customers_id != null) {
				Intent CustomerInfoIntent = new Intent();
				CustomerInfoIntent.putExtra("CustomerId", DocumentClass.Head.customers_id);
				CustomerInfoIntent.setClass(Ctx,Activity_CustomersInfo.class);
		    	startActivity(CustomerInfoIntent);	
			}
			return true;
		}
	};
	
	private OnClickListener ReturnCommentsButton_Click = new OnClickListener() {		
		@Override
		public void onClick(View v) {
					
			Intent Comments = new Intent();
			Comments.setClass(Ctx,MainCommentsActivity.class);
			Comments.putExtra("DocId",  DocumentClass.Head.id);
			Comments.putExtra("Destination_Table",  "xdoc_returns_d");
			Comments.putExtra("Source_Table",  "xenum_ReturnNotes");
			startActivityForResult(Comments, IDR_CommentsSelect);			
			
		}
	};
	
	private void RefreshByDecimalValue (TextView DecimalTextView, Double DecimalValue) {
		
		DecimalTextView.setText(String.format("%.2f", DecimalValue));
		
	}
	
	private OnClickListener ReturnCustomerSelect= new OnClickListener () {	
		
		@Override
		public void onClick(View v) {			
			Intent CustomerSelectintent = new Intent();
			CustomerSelectintent.setClass(Ctx,MainCustomersListActivity.class);
			CustomerSelectintent.putExtra("customer_id", DocumentClass.Head.customers_id);
			CustomerSelectintent.putExtra("customer_descr","");
            startActivityForResult (CustomerSelectintent,IDR_CustomerSelect);			
		}
		
	};
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {	
				 
		 switch(requestCode) { 
		    case IDR_CustomerSelect:
		    	if (resultCode==RESULT_OK) {
		    		ReturnCustomer.setText(data.getStringExtra("customer_descr"));
		    		DocumentClass.Head.state = 1;
		    		DocumentClass.Head.customers_id = data.getStringExtra("customer_id");		    				    		
		    	}
		    	break;  	
		    case IDR_GoodsSelect:
		    	RefreshByDecimalValue (ReturnTotalReturnSum, DocumentClass.Head.total_returnsum);
		    	break;
		    case IDR_CommentsSelect:
		    	DocumentClass.Head.state = 1;
		    	RefreshMultipleByCursor (ReturnComments,"xdoc_Returns_D");
		    	break;
		    	
		 }		 
		    	
	};		
	
	private void RefreshDate (Button DateButton,Date DateValue) {
		SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yy");
		DateButton.setText(sdf.format(DateValue));
	}	
	
	private void RefreshByCursor (Button SelectButton, String Table, String Id) {
		
		try {
			Cursor ScalarCursor = MainGlobalModule.DBE.query (Table, new String []{"descr"}, "id = ?", new String []{Id}, null, null, null);
			ScalarCursor.moveToFirst();
			SelectButton.setText(ScalarCursor.getString(0));
		} catch (Exception e) {
			SelectButton.setText ("");
		}		
	}
	
	private void RefreshMultipleByCursor (Button SelectButton, String Table) {
		
		String StringValues = "";
		try {
			Cursor ScalarCursor = MainGlobalModule.DBE.query (Table, new String []{"descr"}, "hdoc_id = ?", new String []{DocumentClass.Head.id},null,null,null);
			//ScalarCursor.moveToFirst();
			//StringValues.concat(ScalarCursor.getString(0));
			while (ScalarCursor.moveToNext()){
				StringValues = StringValues.concat(ScalarCursor.getString(0))+","; 
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		SelectButton.setText(StringValues);
		
	}
	
	private OnClickListener ReturnDateDialog = new OnClickListener() {		
		@Override
		public void onClick(View v) {
			showDialog(IDD_ReturnDateDialog);			
		}
	};

	private OnClickListener ReturnExecuteDateDialog = new OnClickListener() {		
		@Override
		public void onClick(View v) {
			showDialog(IDD_ReturnExecuteDateDialog);			
		}
	};
	
	private OnClickListener ReturnAccTypeDialog = new OnClickListener() {		
		@Override
		public void onClick(View v) {
			showDialog(IDD_ReturnAccTypeDialog);			
		}
	};
	
	private OnClickListener ReturnFirmDialog = new OnClickListener() {		
		@Override
		public void onClick(View v) {
			showDialog(IDD_ReturnFirmDialog);			
		}
	};

	private OnClickListener ReturnDepartmentDialog = new OnClickListener() {		
		@Override
		public void onClick(View v) {
			showDialog(IDD_ReturnDepartmentDialog);			
		}
	};
	
	@Override
	protected Dialog onCreateDialog(int id) {		
			
			super.onCreateDialog(id);
			
			int mYear;
			int mMonth;
			int mDay;
			
			Calendar C = Calendar.getInstance();
			
			AlertDialog.Builder adb = new AlertDialog.Builder(this);
			
			switch (id) {
			
			case IDD_ReturnDateDialog:
				C.setTime(DocumentClass.Head.date_create);
				mYear = C.get(Calendar.YEAR);
				mMonth = C.get(Calendar.MONTH);
				mDay = C.get(Calendar.DAY_OF_MONTH);			
				return new DatePickerDialog(this, ReturnDateSetListener, mYear, mMonth, mDay);
				
			case IDD_ReturnExecuteDateDialog:
				C.setTime(DocumentClass.Head.date_execute);
				mYear = C.get(Calendar.YEAR);
				mMonth = C.get(Calendar.MONTH);
				mDay = C.get(Calendar.DAY_OF_MONTH);			
				return new DatePickerDialog(this, ReturnExecuteDateSetListener, mYear, mMonth, mDay);

			case IDD_ReturnAccTypeDialog:
				adb.setTitle("Типы Учета");
				adb.setCursor(ReturnAccTypeCursor, ReturnAccTypeDialogClickListener , "descr");
				return adb.create();
				
			case IDD_ReturnFirmDialog:
					adb.setTitle("Фирмы");
					adb.setCursor(ReturnFirmCursor, ReturnFirmDialogClickListener , "descr");
					return adb.create();
			
			case IDD_ReturnDepartmentDialog:	
					adb.setTitle("Склады");
					adb.setCursor(ReturnDepartmentCursor, ReturnDepartmentDialogClickListener , "descr");
					return adb.create();
					
			}
			
			return null;
			
		};
				
	protected void onPrepareDialog(int id, Dialog dialog) {
		super.onPrepareDialog(id, dialog);
		
		int mYear;
		int mMonth;
		int mDay;
		Calendar C = Calendar.getInstance();
		DatePickerDialog M;
		
		switch (id) {
		
		case IDD_ReturnDateDialog:		
			M = (DatePickerDialog)dialog;						
			C.setTime(DocumentClass.Head.date_create);		
			mYear = C.get(Calendar.YEAR);
			mMonth = C.get(Calendar.MONTH);
			mDay = C.get(Calendar.DAY_OF_MONTH);						
			M.updateDate(mYear, mMonth, mDay);
			break;
		case IDD_ReturnExecuteDateDialog:		
			M = (DatePickerDialog)dialog;
			C.setTime(DocumentClass.Head.date_execute);		
			mYear = C.get(Calendar.YEAR);
			mMonth = C.get(Calendar.MONTH);
			mDay = C.get(Calendar.DAY_OF_MONTH);						
			M.updateDate(mYear, mMonth, mDay);
			break;			
			
		}		
		
	}
	
	private OnDateSetListener ReturnDateSetListener = new OnDateSetListener() {		
		@Override
		public void onDateSet(DatePicker view, int year, int month,int day) {						
			Calendar C = Calendar.getInstance();
			C.set(year, month, day);
			DocumentClass.Head.state = 1;
			DocumentClass.Head.date_create = C.getTime();
			RefreshDate (ReturnDate,DocumentClass.Head.date_create);
		}
	};	
	
	private OnDateSetListener ReturnExecuteDateSetListener = new OnDateSetListener() {		
		@Override
		public void onDateSet(DatePicker view, int year, int month,int day) {						
			Calendar C = Calendar.getInstance();
			C.set(year, month, day);
			DocumentClass.Head.state = 1;
			DocumentClass.Head.date_execute = C.getTime();
			RefreshDate (ReturnExecuteDate,DocumentClass.Head.date_execute);
		}
	};	
		
	private DialogInterface.OnClickListener ReturnAccTypeDialogClickListener = new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int which) {
	    	ReturnAccTypeCursor.moveToPosition(which);	    	
	    	ReturnAccType.setText(ReturnAccTypeCursor.getString(1));
	    	DocumentClass.Head.state = 1;
	    	DocumentClass.Head.acctype = ReturnAccTypeCursor.getString(0);	    	
	  }		
	};
	
	private DialogInterface.OnClickListener ReturnFirmDialogClickListener = new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int which) {
	    	ReturnFirmCursor.moveToPosition(which);
	    	ReturnFirm.setText(ReturnFirmCursor.getString(1));
	    	DocumentClass.Head.state = 1;
	    	DocumentClass.Head.firms_id = ReturnFirmCursor.getString(0);
	    }		
	  };
	 
	private DialogInterface.OnClickListener ReturnDepartmentDialogClickListener = new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int which) {
	    	ReturnDepartmentCursor.moveToPosition(which);	    	
	    	ReturnDepartment.setText(ReturnDepartmentCursor.getString(1));
	    	DocumentClass.Head.state = 1;
	    	DocumentClass.Head.departments_id = ReturnDepartmentCursor.getString(0);
	  }		
	};
		
    public boolean onCreateOptionsMenu (Menu menu){
    	menu.add(Menu.NONE,1,Menu.NONE,"Шапка");    	
    	menu.add(Menu.NONE,2,Menu.NONE,"Товары");
    	menu.add(Menu.NONE,3,Menu.NONE,"Подбор");    	
    	menu.add(Menu.NONE,4,Menu.NONE,"Записать");
    	menu.add(Menu.NONE,5,Menu.NONE,"Выход");
		return true;    	
    }
   
    
    private void OpenGoodsSelect () {
    	if (CustomerIsSelect ()) {
    		DocumentClass.Head.state = 1;
    		DocumentClass.UpdateDoc();
    		Intent GoodsCatalog = new Intent();
    		GoodsCatalog.setClass(this,MainGoodsCatalogActivity.class);
    		GoodsCatalog.putExtra("DocType",  MainGlobalModule.DocumentsType.Return);
    		GoodsCatalog.putExtra("DocId",  DocumentClass.Head.id);
    		GoodsCatalog.putExtra("Firm",  DocumentClass.Head.firms_id);
    		GoodsCatalog.putExtra("AccType",  DocumentClass.Head.acctype);
    		GoodsCatalog.putExtra("Department",  DocumentClass.Head.departments_id);
    		GoodsCatalog.putExtra("DocSelection",  1);    			
    		GoodsCatalog.putExtra("SelectOnce",  true);
    		startActivityForResult(GoodsCatalog, IDR_GoodsSelect);	
    	}    	
    }
    
    boolean CustomerIsSelect () {    	
    	if (DocumentClass.Head.customers_id == null ) {
    		Toast.makeText(this, "Необходимо выбрать клиента !!!",Toast.LENGTH_LONG).show();
    		return false;	
    	}    		
    	return true;
    }
    
    private void OpenDocContents () {
    	
    	if (CustomerIsSelect ()) {
    		Intent ReturnContent = new Intent ();
    		ReturnContent.setClass(this, ReturnContentActivity.class);
    		startActivityForResult(ReturnContent, IDR_GoodsSelect);	
    	}
    	
    }
    
    public boolean onOptionsItemSelected (MenuItem item){    	
    	
    	
    	
    	switch (item.getItemId()) {
    		case 2:
    			
    			OpenDocContents ();
    			
    			break;
    			
    		case 3:    			
    			
    			OpenGoodsSelect ();
    			break;    		
    			
    		case 4:  
    			DocumentClass.Head.state = 1;
    			DocumentClass.UpdateDoc();
    			return (true);
    		case 5:    			
    			FinishActivity();
    			return true;
    		}    		
    			return false;    	
    	    
    }
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {		
		
		switch (keyCode){
		
    		case KeyEvent.KEYCODE_BACK:    			
    			return false;   			
    		
    	}	
		return super.onKeyDown(keyCode, event);
	}
	
}
